什么是未定义的参考/未解决的外部符号错误?什么是常见原因以及如何修复/预防它们?
随意编辑/添加您自己的.
c++ c++-faq linker-errors unresolved-external undefined-reference
C和C++有许多不同之处,并非所有有效的C代码都是有效的C++代码.
("有效"是指具有已定义行为的标准代码,即不是特定于实现/未定义/等.)
在使用每种语言的标准编译器编译时,是否有任何一种在C和C++中都有效的代码会产生不同的行为?
为了使它成为一个合理/有用的比较(我试图学习一些实用的东西,而不是试图在问题中找到明显的漏洞),让我们假设:
#ifdef __cplusplus,pragma等) 在对不同尺寸的方形矩阵进行一些实验后,出现了一种模式.转换一个大小的矩阵2^n2^n+1总是比转换一个大小的矩阵慢.对于较小的值n,差异并不重要.
然而,在512的值上会出现很大的差异.(至少对我而言)
免责声明:我知道由于元素的双重交换,函数实际上并没有转置矩阵,但它没有任何区别.
遵循代码:
#define SAMPLES 1000
#define MATSIZE 512
#include <time.h>
#include <iostream>
int mat[MATSIZE][MATSIZE];
void transpose()
{
for ( int i = 0 ; i < MATSIZE ; i++ )
for ( int j = 0 ; j < MATSIZE ; j++ )
{
int aux = mat[i][j];
mat[i][j] = mat[j][i];
mat[j][i] = aux;
}
}
int main()
{
//initialize matrix
for ( int i = 0 ; …Run Code Online (Sandbox Code Playgroud) 我的印象是访问union除最后一个成员之外的成员是UB,但我似乎无法找到一个可靠的参考(除了声称它是UB但没有标准支持的答案).
那么,这是不确定的行为?
第1,2,3,4行有什么区别?
我什么时候使用?
为什么第3行打印constructor Foo和第7行返回错误而第8行没有?
#include <iostream>
using namespace std;
class Foo
{
public:
Foo ( )
{
cout << "constructor Foo\n";
}
};
class Bar
{
public:
Bar ( Foo )
{
cout << "constructor Bar\n";
}
};
int main()
{
/* 1 */ Foo* foo1 = new Foo ();
/* 2 */ Foo* foo2 = new Foo;
/* 3 */ Foo foo3;
/* 4 */ Foo foo4 = Foo::Foo();
/* 5 */ Bar* bar1 = new Bar …Run Code Online (Sandbox Code Playgroud) 根据我的理解,const修饰符应该从右到左阅读.从那以后,我明白了:
const char*
Run Code Online (Sandbox Code Playgroud)
是一个指针,其char元素不能被修改,但指针本身可以,和
char const*
Run Code Online (Sandbox Code Playgroud)
是一个指向mutable字符的常量指针.
但是我得到以下代码的以下错误:
const char* x = new char[20];
x = new char[30]; //this works, as expected
x[0] = 'a'; //gives an error as expected
char const* y = new char[20];
y = new char[20]; //this works, although the pointer should be const (right?)
y[0] = 'a'; //this doesn't although I expect it to work
Run Code Online (Sandbox Code Playgroud)
那么是哪一个呢?我的理解还是我的编译器(VS 2005)错了?
每当类声明仅使用另一个类作为指针时,使用类前向声明而不是包含头文件是否有意义,以便先发制人地避免循环依赖的问题?所以,而不是:
//file C.h
#include "A.h"
#include "B.h"
class C{
A* a;
B b;
...
};
Run Code Online (Sandbox Code Playgroud)
改为:
//file C.h
#include "B.h"
class A;
class C{
A* a;
B b;
...
};
//file C.cpp
#include "C.h"
#include "A.h"
...
Run Code Online (Sandbox Code Playgroud)
有什么理由不尽可能不这样做吗?
我对以下代码中的一些同事存在分歧:
int foo ( int a, int b )
{
return b > 0 ? a / b : a;
}
Run Code Online (Sandbox Code Playgroud)
此代码是否显示未定义的行为?
编辑:分歧开始于过度热切的优化编译器中的错误,其中b > 0检查已经过优化.
在执行指针算术时有很多未定义/未指定行为的示例 - 指针必须指向同一个数组(或者一个超过结尾),或者在同一个对象内,限制何时可以根据上述进行比较/操作等
以下操作定义明确吗?
int* p = 0;
p++;
Run Code Online (Sandbox Code Playgroud) c++ ×10
c ×2
c++-faq ×2
optimization ×2
pointers ×2
class ×1
const ×1
constructor ×1
copy-elision ×1
performance ×1
unions ×1