小编Blu*_*all的帖子

在参数列表中构造一个对象并将指向该对象内部数据的指针传递给函数安全吗?

下面的 C++ 代码格式正确吗?std::string函数执行完成之前还是之后会被销毁?

void my_function(const char*);

...

my_function(std::string("Something").c_str());
Run Code Online (Sandbox Code Playgroud)

我知道我可以做到my_function("Something"),但我用std::string这种方式来说明我的观点。

c++ string temporary-objects

21
推荐指数
1
解决办法
822
查看次数

C++ 析构函数运行两次

请参阅下面的程序。程序应该打印 1,因为 1 计数器对象仍然存在,但是当用 GCC 编译时,它打印 0。为什么呢?这是编译器错误吗?仅当从不同范围返回时才会发生这种情况。删除 if 可以在所有编译器上完全修复它。

#include <iostream>

int counter = 0;

class Counter {
public:
    Counter() {
        counter++;
    }
    ~Counter() {
        counter--;
    }
};

Counter test() {
    if (true) { // REMOVING THIS FIXES IT
        Counter c;
        return c;
    } else {
        throw std::logic_error("Impossible!");
    }
}

int main() {
    Counter c = test();
    std::cout << counter << std::endl; // 0 on GCC (incorrect), 1 on clang (correct)
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

c++ debugging gcc destructor clang

3
推荐指数
1
解决办法
144
查看次数

标签 统计

c++ ×2

clang ×1

debugging ×1

destructor ×1

gcc ×1

string ×1

temporary-objects ×1