error: [chromium-rawptr] Use raw_ptr<T> instead of a raw pointer.

1. 直接禁用掉报错 RAW_PTR_EXCLUSION

例如

 RAW_PTR_EXCLUSION char* bb

 是一个宏,用于在 Chromium 中禁用某个特定的编译错误,特别是与使用原始指针(raw pointer)相关的错误。该错误提示你应该使用 raw_ptr<T> 而不是原始指针。

2. 如果不能使用base库的话,那么 可以考虑使用  std::optional

语法std::optional如下:

std::optional<T> opt_var;

在上面的代码中,T表示要存储的可选值。 主要有三种方法:

  1. has_value:检查对象是否包含值。
  2. value:返回所包含的值。
  3. value_or:如果可用则返回包含的值,否则返回另一个值。

 

#include <iostream>
#include <optional>

std::optional<int> divide(int num1, int num2) {
    if (num2 != 0) {
        return num1/num2;
    }
    return std::nullopt; // Indicates no type-safe value
}

int main() {
    auto result = divide(10, 2); // To infer into std::optional<int>, used to save time 
    if (result.has_value()) {  // has_value checks if a type-value is returned
        std::cout << "Result: " << result.value() << std::endl; // value returns the value as function arguments are correct
    } else {
        std::cout << "Division by zero" << std::endl;
    }

    return 0;
}

 

#include <iostream>
#include <fstream>
#include <optional>
#include <string>

std::optional<std::string> try_reading_file(const std::string& filename) { // const to make sure it doesn't get modified
    std::ifstream file(filename); // std::ifstream for reading files 
    if (!file.is_open()) {  // if file cannot be opened
        return std::nullopt;
    }

    std::string content((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>()); //Written the content inside the file
    return content;
}

int main() {
    const std::string filename = "exmpl.txt";

    // try to read the file
    auto fileContent = try_reading_file(filename);

    if (fileContent.has_value()) {
        std::cout << "File content:\n" << fileContent.value() << std::endl;
    } else {
        std::cerr << "Error: Could not open the file " << filename << std::endl;
    }

    return 0;
}

 

#include <optional>
#include <iostream>

int main() {
    std::optional<int> value;

    int result = value.value_or(42);  // Assigns 42 if value is not present

    std::cout << "Result: " << result << std::endl;

    return 0;
}

 

posted @ 2025-01-02 09:53  冰糖葫芦很乖  阅读(117)  评论(0)    收藏  举报