为什么以下代码会遇到错误“ A”,而无法访问“ B”呢?这是我的想法:
每当我们调用函数foo()时,它将执行new B(5),它将首先调用其基本结构A的构造函数。
struct A的构造函数是一个公共方法,因此它的派生struct B应该可以访问它(如果我没有记错的话,应加以保护)。
然后将调用结构B的构造函数以创建具有五个0的向量。
然后删除对象a将调用析构函数B,然后调用析构函数A。
我的逻辑有什么问题吗?您的回答将不胜感激
#include <iostream>
#include <vector>
using namespace std;
struct A
{
A() { cout << "Constructor A called"<< endl;}
virtual ~A() { cout << "Denstructor A called"<< endl;}
};
struct B : private A
{
vector<double> v;
B(int n) : v(n) { cout << "Constructor B called"<< endl;}
~ B() { cout << "Denstructor B called"<< endl;}
};
int main()
{
const A *a = new …Run Code Online (Sandbox Code Playgroud) 我使用cppcheck分析了一些代码,以了解错误和代码质量。我遇到了一个错误,我认为这是一个误报。下面的代码示例演示了该问题(带有注释)。
cppcheck-1.89版
#include <string>
#include <vector>
#include <iostream>
std::string func() {
std::vector<char> data{};
data.push_back('a');
data.push_back('b');
data.push_back('c');
return std::string{ data.data(), data.size() }; // error marked here
// severity: error
// line: 12
// summary: Returning object that points to local variable 'data' that will be invalid when returning.
}
int main() {
std::string ret{};
{
ret = func();
}
std::cout << ret << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
如果我使用()而不是{},它可以解决该错误。
编辑
当我用()或调试示例时{},完全没有区别。我将Visual Studio 17与C ++ …